import './style.scss'
import { useEffect, useRef } from 'react'
import { useAppSelector, useAppDispatch, AppDispatch } from '@/store';
import canvasSlice, { CanvasSize } from '@/reducers/canvasSlice'
import { renderer } from '@/core/renderer';
import { onAppCanvasReady } from '@/App';

export default () => {
  const wrapperRef = useRef<HTMLDivElement>(null);
  const canvasMainRef = useRef<HTMLCanvasElement>(null);
  const canvasRasterRef = useRef<HTMLCanvasElement>(null);

  const dispatch = useAppDispatch();
  const canvasState = useAppSelector((state) => state.canvas);
  const mainDOMRect = canvasState.mainDOMRect;
  const rasterDOMRect = canvasState.rasterDOMRect;

  useEffect(() => {
    if(canvasMainRef.current) renderer.mountCtx('main', canvasMainRef.current.getContext('2d'))
    if(canvasRasterRef.current) renderer.mountCtx('raster', canvasRasterRef.current.getContext('2d'))
  }, [])

  useEffect(() => {
    const onWindowResize = (callback?: (canvasSize: CanvasSize, dispatch: AppDispatch) => void) => {
      if(wrapperRef.current){
        const wrapperDOMRect = wrapperRef.current.getBoundingClientRect();
        dispatch(canvasSlice.actions.setRaster({
          width: wrapperDOMRect.width,
          height: wrapperDOMRect.height
        }))
        if(typeof callback == 'function') callback({
          width: wrapperDOMRect.width,
          height: wrapperDOMRect.height
        }, dispatch)
      }
    }
    onWindowResize(onAppCanvasReady)

    const onResize = () => onWindowResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [])

  return <>
    <div ref={wrapperRef} className="page-main">
      <canvas 
        ref={canvasMainRef}
        className='canvas-main' 
        width={mainDOMRect.width}
        height={mainDOMRect.height}
      >Your browser does not support canvas or JavaScript is not enabled.</canvas>

      <canvas 
        ref={canvasRasterRef}
        className='canvas-raster' 
        width={rasterDOMRect.width}
        height={rasterDOMRect.height}
      >Your browser does not support canvas or JavaScript is not enabled.</canvas>
    </div>
  </>
}